from lin import db,route_meta,group_required,login_required
from lin.redprint import Redprint
from flask import jsonify
from lin.exception import NotFound,ParameterException,Success
from datetime import datetime,timedelta
from lin.log import Logger

from app.models.classes import Class
from app.validators.forms import BookSearchForm,CreateOrUpdateClassForm
from app.libs.error_code import BookNotFound

class_api = Redprint('classes')

@class_api.route('/<id>',methods=['GET'])
def get_class(id):
    class1 = Class.query.filter_by(id=id).first()
    if class1 is None:
        return NotFound(msg='没有相关信息')
    return jsonify(class1)

@class_api.route('/',methods=['GET'])
@route_meta('查询班次',module='班次')
@group_required
def get_classes():
    classes = []
    classes_ = Class.query.filter_by().all()
    if classes_ is None or len(classes_) < 1:
        raise NotFound(msg='没有相关信息')
    for i in range(len(classes_)):
        if (classes_[i].delete_time==None):
            classes.append(classes_[i])
    return jsonify(classes)


@class_api.route('/create',methods=['POST'])
@route_meta('添加班次',module='班次')
@group_required
def create_class():
    form = CreateOrUpdateClassForm().validate_for_api()
    class1 = Class.query.filter_by(form.name).all()
    for i in range(len(class1)):
        class_date_ = datetime.strftime(class1[i].class_date,'%Y-%m-%d')
        print(class1[i].class_date)
        print(class_date_)
        if str(class_date_) == _datetostring(form.class_date.data):
            raise ParameterException(msg='班次已存在')

    with db.auto_commit():
        new_class = Class()
        new_class.work_id = form.work_id.data
        new_class.name = form.name.data
        new_class.store_id = form.store_id.data
        new_class.store_name = form.store_name.data
        new_class.part = form.part.data
        new_class.class_date = _datetostring(form.class_date.data)
        db.session.add(new_class)
    return Success(msg='新建班次成功')

@class_api.route('/<id>',methods=['PUT'])
@route_meta('调整班次',module='班次')
@group_required
def update_class(id):
    form = CreateOrUpdateClassForm().validate_for_api()
    class1 = Class.query.filter_by(id=id).first()
    if class1 is None:
        raise NotFound()
    with db.auto_commit():
        class1.part = form.part.data
        class1.shift = form.shift.data
        class1.class_date = _datetostring(form.class_date.data)
    return Success(msg='更新班次成功')

@class_api.route('/<id>',methods=['DELETE'])
@route_meta('删除班次',module='班次')
@group_required
def delete_class(id):
    class1: Class = Class.query.filter_by(id=id).first()
    if class1 is None:
        raise NotFound()
    class1.delete(commit=True)
    return Success(msg='删除班次成功')

def _datetostring(dateData):
    date_data = dateData[0]
    date_ = datetime.strptime(date_data,"%Y-%m-%dT%H:%M:%S.%fZ")
    local_time = datetime.strftime((date_ + timedelta(hours=8)),"%Y-%m-%d")
    return local_time
